package com.yunshang.ys.ui.access;

import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yunshang.ys.R;
import com.yunshang.ys.api.AccessApi;
import com.yunshang.ys.api.DownImageApi;
import com.yunshang.ys.base.BaseActivity;
import com.yunshang.ys.utils.UploadPhotoUtil;
import com.yunshang.ys.utils.Validator;
import com.yunshang.ys.ys.YSHttp;
import com.yunshang.ys.ys.YSSubscriber;

import java.util.ArrayList;
import java.util.List;

import cn.finalteam.galleryfinal.GalleryFinal;
//import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

//import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
//import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
//import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultSubscriber;
//import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;

public class RegisterActivity extends BaseActivity {

    TextView tvUnderline;
    ImageView ivHeader;
    TextView tvNation;
    TextView tvPass;
    Button btnRegister;
    EditText etPass;
    private boolean etishide;

    EditText etName;
    EditText etAccount;
    private EditText etPhone;
    private EditText etEmail;
    private EditText etPassRepeat;
    private String headuri; // 相册返回的切图地址


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initstatusbar();
        showTitle("注册").withBack();


        etPass = (EditText) findViewById(R.id.et_pass);
        etPassRepeat = (EditText) findViewById(R.id.et_pass_repeat);
        etName = (EditText) findViewById(R.id.et_name);
        etAccount = (EditText) findViewById(R.id.et_account);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etEmail = (EditText) findViewById(R.id.et_email);


        inittvunderline();


        initclick();
    }

    private void initclick() {

        ivHeader = (ImageView) findViewById(R.id.iv_header);
        ivHeader.setLayoutParams(new TableRow.LayoutParams(
                getResources().getDimensionPixelOffset(R.dimen.y100),
                getResources().getDimensionPixelOffset(R.dimen.y100)
        ));
        ivHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(RegisterActivity.this, "head", Toast.LENGTH_SHORT).show();
                singlepic();
            }
        });
        tvNation = (TextView) findViewById(R.id.tv_nation);
        tvNation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(RegisterActivity.this, "nation", Toast.LENGTH_SHORT).show();
            }
        });
        tvPass = (TextView) findViewById(R.id.tv_pass);
        tvPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(RegisterActivity.this, "pass", Toast.LENGTH_SHORT).show();
                ethidepass();
            }
        });
        btnRegister = (Button) findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                checkformat();
//                Toast.makeText(RegisterActivity.this, "register", Toast.LENGTH_SHORT).show();
//
//                if (!TextUtils.isEmpty(headuri)) {
//                    UploadPhotoUtil uploadPhotoUtil = new UploadPhotoUtil();
//                    List<String> listup = new ArrayList<String>();
//                    listup.add(headuri);
//                    uploadPhotoUtil.uploadPhoto(listup, new UploadPhotoUtil.OnComplete() {
//                        @Override
//                        public void onSuccess(String t,String msg) {
//                        }
//
//                        public void onFail(String msg) {
//                        }
//                    });
//                } else Toast.makeText(RegisterActivity.this, "请选择头像", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 判断各式
     */
    private void checkformat() {

        String namestr = etName.getText().toString().trim();
        String passstr = etPass.getText().toString().trim();
        String accstr = etAccount.getText().toString().trim();
        String phonestr = etPhone.getText().toString().trim();
        String emailstr = etEmail.getText().toString().trim();
        String passRstr = etPassRepeat.getText().toString().trim();
        if (!TextUtils.isEmpty(accstr)) {
            if (Validator.isEmail(accstr) || Validator.isMobile(accstr)) {
                if (!TextUtils.isEmpty(phonestr)) {
                    if (Validator.isMobile(phonestr)) {
                        if (!TextUtils.isEmpty(emailstr)) {
                            if (Validator.isEmail(emailstr)) {
                                if (!TextUtils.isEmpty(passstr)) {
                                    if (Validator.isPassword(passstr)) {
                                        if (passstr.equals(passRstr)) {
                                            if (!TextUtils.isEmpty(namestr)) {

                                                netRegister(
                                                        accstr, namestr,
                                                        "", emailstr,
                                                        phonestr, passRstr);

                                            } else
                                                Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
                                        } else
                                            Toast.makeText(this, "请确认密码一致", Toast.LENGTH_SHORT).show();
                                    } else
                                        Toast.makeText(this, "请输入正确格式的密码", Toast.LENGTH_SHORT).show();
                                } else Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                            } else Toast.makeText(this, "请输入正确的邮箱", Toast.LENGTH_SHORT).show();
                        } else Toast.makeText(this, "请输入邮箱", Toast.LENGTH_SHORT).show();
                    } else Toast.makeText(this, "请输入正确的手机", Toast.LENGTH_SHORT).show();
                } else Toast.makeText(this, "请输入手机", Toast.LENGTH_SHORT).show();
            } else Toast.makeText(this, "请输入正确的账号", Toast.LENGTH_SHORT).show();
        } else Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();


    }


    /**
     * 注册接口
     */
    private void netRegister(String accstr, String namestr,
                             String iconstr, String emailstr,
                             String phonestr, String passRstr) {

        YSHttp.createApi(AccessApi.class)
                .netRegister(accstr, namestr,
                        iconstr, emailstr,
                        phonestr, passRstr)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new YSSubscriber<String>() {
                    @Override
                    public void onSuccess(String t,String msg) {
                        System.out.println("rrrrrrrrrrrr " + t);
                        System.out.println("tttttttttttt " + msg);
                        Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFail(String msg) {
                        System.out.println("msgmsgmsgmsg " + msg);
                        Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void singlepic() {

        GalleryFinal.openGallerySingle(200, mOnHanlderResultCallback);
        //自定义方法的单选
//        RxGalleryFinal
//                .with(getApplicationContext())
//                .image()
//                .radio()
//                .crop()
//                .imageLoader(ImageLoaderType.GLIDE)
//                .subscribe(new RxBusResultSubscriber<ImageRadioResultEvent>() {
//                    @Override
//                    protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
//                        //图片选择结果
//                        String cropPath = imageRadioResultEvent.getResult().getCropPath();
//                        System.out.println("pppppppppp " + cropPath);
////                        ivHeader.set
//                    }
//                })
//                .openGallery();
    }

    private void ethidepass() {
        if (etishide) {
            etishide = false;
            // hide
            etPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//            etPass.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {
            etishide = true;
            // show
            etPass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//            etPass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());

        }
    }

    private void inittvunderline() {

        tvUnderline = (TextView) findViewById(R.id.tv_underline);
        tvUnderline.setText("点击上面的“注册按钮，即表示你同意");
        String uline = "《云上科创软件许可及服务协议》";

        SpannableString spStr = new SpannableString(uline);


//        URLSpan[] urls = spStr.getSpans( 0, uline.length(), URLSpan.class );
//        spStr.setSpan(new ForegroundColorSpan(Color.RED), spStr.getSpanStart(urls), spStr.getSpanEnd(urls), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//设置前景色为红色


        spStr.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
//                ds.setColor(Color.WHITE);       //设置文件颜色
                ds.setUnderlineText(true);      //设置下划线
            }

            @Override
            public void onClick(View widget) {
                Toast.makeText(RegisterActivity.this, "《云上科创软件许可及服务协议》《云上科创软件许可及服务协议》《云上科创软件许可及服务协议》《云上科创软件许可及服务协议》", Toast.LENGTH_SHORT).show();
            }
        }, 0, uline.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvUnderline.setHighlightColor(Color.TRANSPARENT); //设置点击后的颜色为透明，否则会一直出现高亮
        tvUnderline.append(spStr);
        tvUnderline.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
    }


    /**
     * galleryfinally
     */
    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int i, List<PhotoInfo> list) {
            if (list != null) {
//                if (i == 100) {
//                    Logger.e("openCamera");
//                } else if (i == 200) {
//                    Logger.e("openGallerySingle");
//                }
                System.out.println("pppppppppppp " + list.get(0).getPhotoPath());
                headuri = list.get(0).getPhotoPath();
                PhotoInfo photoInfo = list.get(0);

                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showImageOnFail(R.drawable.ic_gf_default_photo)
                        .showImageForEmptyUri(R.drawable.ic_gf_default_photo)
                        .showImageOnLoading(R.drawable.ic_gf_default_photo).build();
                ImageLoader.getInstance().displayImage("file:/" + list.get(0).getPhotoPath(), ivHeader, options);
//                Glide.with(getApplicationContext()).load(list.get(0).getPhotoPath()).into(ivHeader);

            }
        }

        @Override
        public void onHanlderFailure(int i, String s) {
            Toast.makeText(RegisterActivity.this, s, Toast.LENGTH_SHORT).show();
        }
    };
    // galleryfinally
}
